<template>
  <div>
    <!-- 三级分类展示 -->
    <el-card>
      <el-form :inline="true">

       <Category :scene="scene"></Category>

      </el-form>
    </el-card>
    <el-card style="margin: 10px 0px;">
      <!-- 展示请求回来的数据 -->
     <div v-show="scene==0">
       <el-button type="primary" icon="Plus" :disabled="!categoryStore.c3Id" @click="addAttr" v-has="`btn.Attr.add`">添加属性</el-button>
        <el-table border style="margin: 10px 0px;" :data="attrArr">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #='{row,$index}'>
              <el-tag style="margin: 5px;" v-for="(item,index) in row.attrValueList" :key="item.id">{{ item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作"  width="120px">
            <template #='{row,$index}'>
              <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)" v-has="`btn.Attr.update`"></el-button>
              
              
                <el-popconfirm :title="`确认删除${row.attrName}?`" width="200px" @confirm="deleteAttr(row.id)">
                  <template #reference>
                    <el-button type="danger" size="small" icon="Delete" v-has="`btn.Attr.remove`"></el-button>
                  </template>
                </el-popconfirm>
              
            </template>
          </el-table-column>
        </el-table>
     </div>
     <!-- 修改属性页面 -->
     <div v-show="scene==1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性名" v-model="attrParams.attrName"</el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addAttrValue" :disabled="!attrParams.attrName" type="primary" size="default" icon="Plus">添加属性值</el-button>
        <el-button  size="default" @click="cancel">取消</el-button>
        <el-table border style="margin: 10px 0px;" :data="attrParams.attrValueList">
          <el-table-column align="center" width="80px" type="index" label="序号"></el-table-column>
          <el-table-column label="属性值">
            <template #="{row,$index}">
              <el-input :ref="(vc:any)=>inputArr[$index]=vc" v-if="row.flag"  @blur="toLook(row,$index)" placeholder="请输入属性值名" v-model="row.valueName"></el-input>
              <div @click="toEdit(row,$index)" v-else>{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{row,$index}">
              <el-button type="warning"  size="small" @click="attrParams.attrValueList.splice($index,1)" icon="Delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save"  size="default" :disabled="attrParams.attrValueList.length>0?false:true">保存</el-button>
        <el-button  size="default" @click="cancel">取消</el-button>
     </div>
    </el-card>
  </div>
</template>

<script setup lang='ts'>
import { ref,reactive,onMounted,watch,nextTick,onBeforeMount } from 'vue';
import { reqAttr,reqAddOrUpdateAttr,reqRemoveAttr } from '@/api/product/attr';
import type { AttrResponseData,AttrList ,Attr,AttrValue} from '@/api/product/attr/type';
//引入小仓库
import useCategoryStore from '@/store/modules/category'
import { ElMessage } from 'element-plus';
let categoryStore=useCategoryStore()
//存储属性数据
let attrArr=ref<AttrList>([])
//定义card组件内容切换
let scene=ref<number>(0) //当scene=0时，显示table，是=1时：显示添加属性页面
//存储新增属性
let attrParams=reactive<Attr>({
  attrName:"", //新增属性名字
  attrValueList:[  //新增属性值数组   

  ],
  categoryId:'',  //三级分类ID
  categoryLevel:3 //代表的是二级分类
})
//控制编辑模式与查看模式的切换
let flag=ref<boolean>(true)
//准备一个空数组来存储对应的组件实例el-input
let inputArr=ref<any>([])

//监听三级下拉菜单的id，此id有了就发请求捞对应数据
watch(()=>categoryStore.c3Id,()=>{
  //id变化之前把上一次请求回来的数据清空
  attrArr.value=[]
  //保证有三级分类id的情况下才发请求，否则三级分类id从有变为空串从而导致发一次无效请求
  if(!categoryStore.c3Id) return;
  getAttr()
})
//获取已有属性值和属性方法
const getAttr=async()=>{
  const {c1Id,c2Id,c3Id}=categoryStore
  let result:AttrResponseData = await reqAttr(c1Id,c2Id,c3Id)
  if(result.code==200){
    attrArr.value=result.data
  }
  
}

//添加按钮的回调
const addAttr=()=>{
  //点击添加时将上一次输入框内数据清空
  Object.assign(attrParams,{
      attrName:"", //新增属性名字
      attrValueList:[  //新增属性值数组   

      ],
      categoryId:'',  //三级分类ID
      categoryLevel:3 //代表的是三级分类
  })
  scene.value=1,
  //在此时手机三级分类的id
  attrParams.categoryId=categoryStore.c3Id
}
//修改按钮的回调
const updateAttr=(row:Attr)=>{
  scene.value=1
  //将已有属性值赋值给attrParsms对象
  //ES6对象赋值
  //一个坑，不能用浅拷贝，必须深拷贝
  // Object.assign(attrParams,row)
  //深拷贝：用的json
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))

} 
//删除按钮回调
const deleteAttr=async(id:number)=>{
   let result= await reqRemoveAttr(id)
   if(result.code==200){
     ElMessage({
          type:"success",
          message:'删除成功'
        })
      //重新获取数据
    getAttr()
   }else{
    ElMessage({
          type:"error",
          message:'删除失败'
        })
   }
   
}
//取消按钮回调
const cancel=()=>{
  scene.value=0
}
//添加属性值回调
const addAttrValue=()=>{
  attrParams.attrValueList.push({
    valueName:'',
    flag:true   //控制编辑模式与查看模式的切换
})
    //点击聚焦
    nextTick(()=>{
      inputArr.value[attrParams.attrValueList.length-1].focus();
    })
}
//保存按钮回调--发请求
const save=async()=>{
    let result= await reqAddOrUpdateAttr(attrParams)
    if(result.code==200){
        scene.value=0 
        ElMessage({
          type:"success",
          message:attrParams.id?'修改成功':'添加成功'
        })
        //在获取 一次所有信息
        getAttr()
      }else{
        ElMessage({
          type:"error",
          message:attrParams.id?'修改失败':'添加失败'
        })
      }
    }
//编辑状态失去焦点时
const toLook=(row:AttrValue,$index:number)=>{
  //非法输入判断
  if(row.valueName.trim()==''){
    //删除对应属性值为空的元素
    attrParams.attrValueList.splice($index,1)
    ElMessage({
          type:"error",
          message:'属性值不能为空'
        })
  }
  //非法情况二：不能输入重复的属性值
  let repeat=attrParams.attrValueList.find((item)=>{
    //把当前失去焦点的属性值对象剔除
    if(item!=row){
      return item.valueName===row.valueName
    }
  })
  if(repeat){
     ElMessage({
          type:"error",
          message:'属性值不能重复'
        })
        //清空重复的属性值
        attrParams.attrValueList.splice($index,1)
  }
  row.flag=false
}
//查看状态
const toEdit=(row:AttrValue,$index:number)=>{
   row.flag=true
    //点击聚焦
    nextTick(()=>{
      inputArr.value[$index].focus();
    })
}

//组件销毁前清除数据
onBeforeMount(()=>{
  //清空仓库数据 :  $reset()方法课清空仓库
  categoryStore.$reset()
})
   
</script>



<style scoped lang='scss'>
.el-form--inline {
  .el-form-item {
    & > .el-input, .el-cascader, .el-select, .el-date-editor, .el-autocomplete {
      width: 240px;
    }
  }
}
</style>